package org.bingdianleil.stock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

import javax.annotation.Resource;

import org.bingdianleil.config.MultiThreadConfig;
import org.bingdianleil.service.HttpAPIService;
import org.bingdianleil.stock.dao.StockDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@Configuration
@EnableScheduling
public class StockHistory {

	@Resource
	private MultiThreadConfig executor;

	@Resource
	private HttpAPIService httpAPIService;

	@Autowired
	private StockDao stockDao;

	@Value("${stock.baseUrl}")
	private String baseUrl;

	List<Future> futures = new ArrayList<>();

	/**
	 * 股票数据插入
	 * 
	 * @author liulei
	 *
	 */
	class StockProcess implements Runnable {

		String stock;

		public StockProcess(String stock) {
			this.stock = stock;
		}

		@Override
		public void run() {
			getStock(stock);

		}

		public void getStock(String stock) {
			try {
				String responseBody = httpAPIService.doGet(baseUrl + stock);
				List<String> stockList = new ArrayList<String>();
				for (String code : responseBody.split(";")) {
					code = code.trim();
					if (code != null && !"".equals(code) && code.indexOf("\"") + 1 != code.lastIndexOf("\"")) {
						System.out.println(code);
						String data = code.substring(code.lastIndexOf("_") + 1, code.indexOf("=")) + ","
								+ code.substring(code.indexOf("\"") + 1, code.lastIndexOf("\""));
						stockList.add(data);
					} else {
						System.out.println(code);
					}
				}

				stockDao.insertStock(stockList);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	@Scheduled(cron = "0 0/1 8,9,10,11,12,13,14,15 * * ?")
	public void getStockList() {
		List<String> stockList = stockDao.getStock(null);
		StringBuffer stock = new StringBuffer();
		for (int i = 0; i < stockList.size(); i++) {
			if (i % 100 == 0 && i != 0) {
				stock.deleteCharAt(stock.length() - 1);
				Future<?> future = executor.defaultThreadPool().submit(new StockProcess(stock.toString()));
				futures.add(future);
				stock = new StringBuffer();
			} else {
				stock.append(processStock(stockList.get(i).trim()) + ",");
			}
		}
		if (stock.length() > 0) {
			stock.deleteCharAt(stock.length() - 1);
			System.out.println(stock.toString());
			Future<?> future = executor.defaultThreadPool().submit(new StockProcess(stock.toString()));
			futures.add(future);
		}

	}

	public static String processStock(String stock) {
		int length = stock.length();
		return stock.substring(length - 2, length).toLowerCase() + stock.substring(0, length - 3);
	}

}
